package nc.impl.pub.service;


import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;
import javax.swing.tree.TreeNode;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import nc.bs.framework.common.NCLocator;
import nc.bs.pub.filesystem.IFileSystemService;
import nc.bs.pub.filesystem.IQueryFolderTreeNodeService;
import nc.itf.pub.dbservice.IDBService;
import nc.itf.pub.service.INCCAttachSyncService;
import nc.vo.pub.BusinessException;
import nc.vo.pub.filesystem.FileTypeConst;
import nc.vo.pub.filesystem.NCFileNode;
import nc.vo.pub.filesystem.NCFileVO;
import nc.vo.pub.lang.UFBoolean;
import nccloud.bs.log.ImplLogVO;
import nccloud.pubitf.platform.attachment.IAttachmentService;
import nccloud.pubitf.platform.attachment.IFileStorageConst;
import nccloud.pubitf.platform.attachment.sync.ISMFileCloudSyncService;
import nccloud.pubitf.platform.attachment.sync.SMFileCloudSyncVO;
import uap.pub.fs.domain.basic.FileHeader;

/**
 * 附件同步服务实现类
 * @author wy
 * @date 2025年9月21日
 */
public class NCCAttachSyncServiceImpl implements INCCAttachSyncService {
    private IQueryFolderTreeNodeService queryFolderTreeNodeService;
    private IFileSystemService fileSystemService;
    private IAttachmentService attachmentService;
    private IDBService dbService;

    @Override
    public void createAttNode(String folderName, String parentPath, String userid)
            throws BusinessException {
        IFileSystemService fservice = NCLocator.getInstance().lookup(IFileSystemService.class);
        fservice.createNewFileNode(parentPath, folderName,userid);
    }

    @Override
    public void fileUpload(String fullPath, String billID, String vbillcode, List<String> fileURLs, String pk_group,
                           String pk_org, String pk_org_v, String pk_billtypeid, String cuserid) throws BusinessException {

        List<String> filePaths = new ArrayList<String>();
        if (fileURLs == null || fileURLs.isEmpty())
            return; // 需要上传的附件为空
        String newBucket = getStorePath(null);
        List<ImplLogVO> succvos = new ArrayList<ImplLogVO>();
        List<ImplLogVO> errorvos = new ArrayList<ImplLogVO>();
        for (String obj : fileURLs) {
            JSONObject json = JSON.parseObject(obj);
            String fileURL = json.getString("url");
            // 特殊字符转义
            String attachmentName = json.getString("filename").replaceAll("[<>:\"/\\\\|?*]", "_");
            ImplLogVO logvo  = NccAttachmentFileUploadUtil.setDefaultLogVO(fileURL, pk_group, pk_org, pk_org_v, pk_billtypeid);
            URL url = null;
            URLConnection conn = null;
            InputStream inputStream = null;
            try {
                try {
                    url = new URL(fileURL);
                    conn = url.openConnection();
                    inputStream = conn.getInputStream();
                }catch(Exception e) {
                    throw new Exception("附件地址["+fileURL+"]不合理, 异常信息:" + e.getMessage());
                }
                FileHeader header = getAttachmentService().upload(attachmentName, inputStream, false, 0, newBucket);
                saveDBInfo(fullPath, header,cuserid);
                filePaths.add(fullPath + "/" + header.getName());
                logvo.setError("附件下载成功");
                logvo.setIssuccess("Y");
                succvos.add(logvo);
            } catch (Exception e) {
                logvo.setError("附件保存数据库异常:" + e.getMessage());
                logvo.setIssuccess("N");
                errorvos.add(logvo);
                throw new BusinessException(e);
            }finally {
                if(inputStream != null ) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        if(succvos != null  && !succvos.isEmpty()) {
            getDbService().insertVOList(succvos);
        }
        if(errorvos != null && !errorvos.isEmpty()) {
            getDbService().insertVOList(errorvos);
        }

    }

    @Override
    public void fileUploadURL(String fullPath, String billID, String vbillcode, List<String> fileURLs, String pk_group, String pk_org, String pk_org_v, String pk_billtypeid, String cuserid) throws BusinessException {
        List<String> filePaths = new ArrayList<String>();
        if (fileURLs == null || fileURLs.isEmpty())
            return; // 需要上传的附件为空
        List<ImplLogVO> succvos = new ArrayList<ImplLogVO>();
        List<ImplLogVO> errorvos = new ArrayList<ImplLogVO>();
        for (String obj : fileURLs) {
            JSONObject json = JSON.parseObject(obj);
            String fileURL = json.getString("url");
            // 特殊字符转义
            String attachmentName = json.getString("filename").replaceAll("[<>:\"/\\\\|?*]", "_");
            ImplLogVO logvo  = NccAttachmentFileUploadUtil.setDefaultLogVO(fileURL, pk_group, pk_org, pk_org_v, pk_billtypeid);
            try {
                NCFileVO newfilevo = new NCFileVO();
                newfilevo.setCreator(cuserid);
                newfilevo.setPath(fullPath + "/" + attachmentName+".url"); // 默认格式 文件名.url
                newfilevo.setFolder(false);
                newfilevo.setFiletype(FileTypeConst.URL);
                newfilevo.setTime((new Date()).getTime());
                newfilevo.setDirty(UFBoolean.FALSE.isValue());
                newfilevo.setFileLen(0);
                newfilevo.setPk_doc(fileURL);
                this.getFileSystemService().insertURLFileVO(newfilevo);
                this.getAttachmentService().saveFileLog(fullPath, newfilevo);
            } catch (Exception e) {
                logvo.setError("附件保存数据库异常:" + e.getMessage());
                logvo.setIssuccess("N");
                errorvos.add(logvo);
                throw new BusinessException(e);
            }
        }
        if(succvos != null  && !succvos.isEmpty()) {
            getDbService().insertVOList(succvos);
        }
        if(errorvos != null && !errorvos.isEmpty()) {
            getDbService().insertVOList(errorvos);
        }
    }

    @Override
    public void fileUploadNC(String fullPath, String billID, String vbillcode, List<String> fileURLs, String pk_group,
                             String pk_org, String pk_org_v, String pk_billtypeid, String cuserid) throws BusinessException {
        List<String> filePaths = new ArrayList<String>();
        if (fileURLs == null || fileURLs.isEmpty())
            return; // 需要上传的附件为空
        String newBucket = getStorePath(null);
        List<ImplLogVO> succvos = new ArrayList<ImplLogVO>();
        List<ImplLogVO> errorvos = new ArrayList<ImplLogVO>();
        for (String obj : fileURLs) {
            JSONObject json = JSON.parseObject(obj);
            String fileURL = json.getString("attachmentPath");
            String type = json.getString("attachmentType");
            String name = json.getString("attachmentName");

            String attname =  name+"."+ type;
            // 特殊字符转义
            String attachmentName = attname.replaceAll("[<>:\"/\\\\|?*]", "_");
            ImplLogVO logvo  = NccAttachmentFileUploadUtil.setDefaultLogVO(fileURL, pk_group, pk_org, pk_org_v, pk_billtypeid);
            URL url = null;
            URLConnection conn = null;
            InputStream inputStream = null;
            try {
                try {
                    url = new URL(fileURL);
                    conn = url.openConnection();
                    inputStream = conn.getInputStream();
                }catch(Exception e) {
                    throw new Exception("附件地址["+fileURL+"]不合理, 异常信息:" + e.getMessage());
                }
                FileHeader header = getAttachmentService().upload(attachmentName, inputStream, false, 0, newBucket);
                saveDBInfo(fullPath, header,cuserid);
                filePaths.add(fullPath + "/" + header.getName());
                logvo.setError("附件下载成功");
                logvo.setIssuccess("Y");
                succvos.add(logvo);
            } catch (Exception e) {
                logvo.setError("附件保存数据库异常:" + e.getMessage());
                logvo.setIssuccess("N");
                errorvos.add(logvo);
                throw new BusinessException(e);
            }finally {
                if(inputStream != null ) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        if(succvos != null  && !succvos.isEmpty()) {
            getDbService().insertVOList(succvos);
        }
        if(errorvos != null && !errorvos.isEmpty()) {
            getDbService().insertVOList(errorvos);
        }
    }

    @Override
    public void fileUploadHOPG(String fullPath, String billID, String vbillcode, List<String> fileURLs, String pk_group,
                             String pk_org, String pk_org_v, String pk_billtypeid, String cuserid) throws BusinessException {
        List<String> filePaths = new ArrayList<String>();
        if (fileURLs == null || fileURLs.isEmpty())
            return; // 需要上传的附件为空
        String newBucket = getStorePath(null);
        List<ImplLogVO> succvos = new ArrayList<ImplLogVO>();
        List<ImplLogVO> errorvos = new ArrayList<ImplLogVO>();
        for (String obj : fileURLs) {
            JSONObject json = JSON.parseObject(obj);
            String fileURL = json.getString("attachmentPath");
            String type = json.getString("attachmentType");
            String name = json.getString("attachmentName");

            String attname =  name+"."+ type;
            // 特殊字符转义
            String attachmentName = attname.replaceAll("[<>:\"/\\\\|?*]", "_");
            ImplLogVO logvo  = NccAttachmentFileUploadUtil.setDefaultLogVO(fileURL, pk_group, pk_org, pk_org_v, pk_billtypeid);
            URL url = null;
            URLConnection conn = null;
            InputStream inputStream = null;
            try {
                try {
                    url = new URL(fileURL);
                    conn = url.openConnection();
                    inputStream = conn.getInputStream();
                }catch(Exception e) {
                    throw new Exception("附件地址["+fileURL+"]不合理, 异常信息:" + e.getMessage());
                }
                FileHeader header = getAttachmentService().upload(attachmentName, inputStream, false, 0, newBucket);
                saveDBInfo(fullPath, header, cuserid);
                filePaths.add(fullPath + "/" + header.getName());
                logvo.setError("附件下载成功");
                logvo.setIssuccess("Y");
                succvos.add(logvo);
            } catch (Exception e) {
                logvo.setError("附件保存数据库异常:" + e.getMessage());
                logvo.setIssuccess("N");
                errorvos.add(logvo);
                throw new BusinessException(e);
            }finally {
                if(inputStream != null ) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        if(succvos != null  && !succvos.isEmpty()) {
            getDbService().insertVOList(succvos);
        }
        if(errorvos != null && !errorvos.isEmpty()) {
            getDbService().insertVOList(errorvos);
        }
    }

    @Override
    public void fileUploadFileBase64(String pk_group, String pk_org, String pk_org_v, String pk_billtypeid,String pk_billid,String createUserid, JSONArray arrs) throws BusinessException {
        List<String> filePaths = new ArrayList<String>();
        if (null == arrs || arrs.isEmpty()) return; // 需要上传的附件为空
        String newBucket = getStorePath(null);
        List<ImplLogVO> succvos = new ArrayList<ImplLogVO>();
        List<ImplLogVO> errorvos = new ArrayList<ImplLogVO>();
        for (Object obj : arrs) {
            JSONObject json = JSON.parseObject(obj.toString());
            String content = json.getString("content");
            String type = json.getString("filetype");
            String name = json.getString("filename");

            String attname =  name+"."+ type;
            // 特殊字符转义
            String attachmentName = attname.replaceAll("[<>:\"/\\\\|?*]", "_");
            ImplLogVO logvo  = NccAttachmentFileUploadUtil.setDefaultLogVO(attachmentName, pk_group, pk_org, pk_org_v, pk_billtypeid);
            InputStream inputStream = null;
            try {
                inputStream = this.FileBase64ConvertInputStream(content);
                FileHeader header = getAttachmentService().upload(attachmentName, inputStream, false, 0, newBucket);
                saveDBInfo(pk_billid, header, createUserid);
                filePaths.add(pk_billid + "/" + header.getName());
                logvo.setError("附件下载成功");
                logvo.setIssuccess("Y");
                succvos.add(logvo);
            } catch (Exception e) {
                logvo.setError("附件保存数据库异常:" + e.getMessage());
                logvo.setIssuccess("N");
                errorvos.add(logvo);
                throw new BusinessException(e);
            }finally {
                if(inputStream != null ) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        if(succvos != null  && !succvos.isEmpty()) {
            getDbService().insertVOList(succvos);
        }
        if(errorvos != null && !errorvos.isEmpty()) {
            getDbService().insertVOList(errorvos);
        }
    }

    @Override
    public void fileUploadFileInputStream(String pk_group, String pk_org, String pk_org_v, String pk_billtypeid,String pk_billid,String createUserid,String fileName,String fileType, InputStream inputStream) throws BusinessException {
        List<String> filePaths = new ArrayList<String>();
        if (null == inputStream) return; // 需要上传的附件为空
        String newBucket = getStorePath(null);
        List<ImplLogVO> succvos = new ArrayList<ImplLogVO>();
        List<ImplLogVO> errorvos = new ArrayList<ImplLogVO>();
        String attname =  fileName+"."+ fileType;
        // 特殊字符转义
        String attachmentName = attname.replaceAll("[<>:\"/\\\\|?*]", "_");
        ImplLogVO logvo  = NccAttachmentFileUploadUtil.setDefaultLogVO(attname, pk_group, pk_org, pk_org_v, pk_billtypeid);
        try {
            FileHeader header = getAttachmentService().upload(attachmentName, inputStream, false, 0, newBucket);
            saveDBInfo(pk_billid, header,createUserid);
            filePaths.add(pk_billid + "/" + header.getName());
            logvo.setError("附件下载成功");
            logvo.setIssuccess("Y");
            succvos.add(logvo);
        } catch (Exception e) {
            logvo.setError("附件保存数据库异常:" + e.getMessage());
            logvo.setIssuccess("N");
            errorvos.add(logvo);
            throw new BusinessException(e);
        }finally {
            if(inputStream != null ) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        if(succvos != null  && !succvos.isEmpty()) {
            getDbService().insertVOList(succvos);
        }
        if(errorvos != null && !errorvos.isEmpty()) {
            getDbService().insertVOList(errorvos);
        }
    }
    /**
     * 将Base64字符串转换为InputStream
     * @param base64String Base64格式的字符串
     * @return 转换后的InputStream，如果输入为空则返回null
     */
    public InputStream FileBase64ConvertInputStream(String base64String) {
        if (base64String == null || base64String.isEmpty()) {
            return null;
        }
        // 解码Base64字符串为字节数组
        byte[] decodedBytes = Base64.getDecoder().decode(base64String);
        // 将字节数组转换为InputStream
        return new ByteArrayInputStream(decodedBytes);
    }
    private String getStorePath(String[] storepaths) {
        String storepath = IFileStorageConst.Bucket;
        if (storepaths != null && storepaths.length > 0 && storepaths[0] != null && !"".equals(storepaths[0])) {
            storepath = storepaths[0];
        }
        return storepath;
    }

    private NCFileNode saveDBInfo(String fullPath, FileHeader header, String cuserid) {
        IAttachmentService ncservice = NCLocator.getInstance().lookup(IAttachmentService.class);
        NCFileVO attach = new NCFileVO();
        attach.setPath(header.getName());
        attach.setCreator(cuserid);
        attach.setFileLen(header.getFileSize().longValue());
        attach.setPk_doc(header.getPath());
        attach.setIsdoc("z");
        return ncservice.saveAttachDBInfo(fullPath, attach);
    }

    private boolean CheckTheSameFileName(TreeNode node, String filename) {
        for (int noden = 0; noden < node.getChildCount(); noden++) {
            TreeNode subnode = node.getChildAt(noden);
            if (filename.trim().equalsIgnoreCase(subnode.toString().trim())) {
                return true;
            }
        }
        return false;
    }

    public IQueryFolderTreeNodeService getQueryFolderTreeNodeService() {
        if (queryFolderTreeNodeService == null) {
            queryFolderTreeNodeService = NCLocator.getInstance().lookup(IQueryFolderTreeNodeService.class);
        }
        return queryFolderTreeNodeService;
    }

    public IFileSystemService getFileSystemService() {
        if (fileSystemService == null) {
            fileSystemService = NCLocator.getInstance().lookup(IFileSystemService.class);
        }
        return fileSystemService;
    }

    public IAttachmentService getAttachmentService() {
        if (attachmentService == null) {
            attachmentService = NCLocator.getInstance().lookup(IAttachmentService.class);
        }
        return attachmentService;
    }

    public IDBService getDbService() {
        if (dbService == null) {
            dbService = NCLocator.getInstance().lookup(IDBService.class);
        }
        return dbService;
    }
}
